﻿using System;
using System.Collections.Generic;
using System.Text;

namespace DusonFramework.DataAccess.Utility
{
    using System.Reflection;
    using System.Configuration;

    public class SQLFactory
    {
        private static string _assemblyPath = ConfigurationManager.AppSettings["DAL"];

        public static string AssemblyPath
        {
            get { return _assemblyPath; }
            set { _assemblyPath = value; }
        }

        #region CreateObject

        //不使用缓存
        private static object CreateObjectNoCache(string assemblyPath, string CacheKey)
        {
            try
            {
                object objType = Assembly.Load(assemblyPath).CreateInstance(CacheKey);
                return objType;
            }
            catch
            {
                return null;
            }
        }

        //使用缓存
        private static object CreateObject(string assemblyPath, string CacheKey)
        {
            object objType = DataCache.GetCache(CacheKey);
            if (objType == null)
            {
                try
                {
                    objType = Assembly.Load(assemblyPath).CreateInstance(CacheKey);
                    DataCache.SetCache(CacheKey, objType);// 写入缓存
                }
                catch
                {
                    return null;
                }
            }

            return objType;
        }
        #endregion

        // 生成实例
        public static object CreateInstance(string className)
        {
            string CacheKey = AssemblyPath + "." + className;
            object objType = CreateObject(AssemblyPath, CacheKey);
            return objType;
        }

    }

    /// <summary>
    /// 缓存相关的操作类
    /// </summary>
    public class DataCache
    {
        /// <summary>
        /// 获取当前应用程序指定CacheKey的Cache值
        /// </summary>
        /// <param name="CacheKey"></param>
        /// <returns></returns>
        public static object GetCache(string CacheKey)
        {
            System.Web.Caching.Cache objCache = System.Web.HttpRuntime.Cache;
            return objCache[CacheKey];
        }

        /// <summary>
        /// 设置当前应用程序指定CacheKey的Cache值
        /// </summary>
        /// <param name="CacheKey"></param>
        /// <param name="objObject"></param>
        public static void SetCache(string CacheKey, object objObject)
        {
            System.Web.Caching.Cache objCache = System.Web.HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject);
        }
    }

}
